package com.dove.config;

import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import javax.swing.*;
import java.time.Duration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

@Configuration
@EnableCaching
public class redisConfig {
    //设置序列化Bean
    @Bean("json")
    public RedisTemplate<Object,Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){
        //创建RedisTemplate模板
        RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
        //关联RedisConnectionFactory
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        //创建序列化类
        Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<>(Object.class);
        //序列化类对象映射设置
        //设置value的转化格式和key的转化格式
        redisTemplate.setValueSerializer(serializer);
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }
    @Bean("base")
    public  RedisTemplate<Object,Object> redisTemplateBase(RedisConnectionFactory redisConnectionFactory){
        RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        return redisTemplate;
    }
    //设置缓存的Bean
    @Bean
    public RedisCacheManager redisCacheManager(RedisConnectionFactory redisConnectionFactory){
        //创建缓存空间
        Set<String> cacheNames = new HashSet<>();
        //命名空间对应controller
        cacheNames.add("user");
        //对每个空间进行配置
        Map<String, RedisCacheConfiguration> configMap = new HashMap<>();
        RedisCacheConfiguration articlesConfig = RedisCacheConfiguration.defaultCacheConfig()
                //设置缓存时间
                .entryTtl(Duration.ofSeconds(20))
                //禁止缓存空数据
                .disableCachingNullValues();
        //将配置和缓存空间进行关联
        configMap.put("user", articlesConfig);

        return RedisCacheManager.builder(redisConnectionFactory)
                .cacheDefaults(articlesConfig)
                .initialCacheNames(cacheNames)
                .withInitialCacheConfigurations(configMap)
                .build();
    }
}
